package com.senior.sendmessage.service.impl.wechat;

import cn.hutool.core.util.StrUtil;
import com.senior.sendmessage.config.WeChatMessageRouter;
import com.senior.sendmessage.service.wechat.WeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Baijl
 * @version 0.0.1
 * @date 2021-11-28 15:59
 * @description TODO
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WeChatServiceImpl implements WeChatService {
    private final WxMpService wxMpService;
    private final WeChatMessageRouter weChatMessageRouter;


    @Override
    public String receiveMsg(HttpServletRequest request) throws IOException {
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String msgSignature = request.getParameter("msg_signature");
        WxMpXmlMessage wxMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
        log.info("展示对象；{}", wxMessage);
        WxMpXmlOutMessage route = weChatMessageRouter.getRouter(wxMpService).route(wxMessage);
        log.info("加密后router{}", route);

        return route.toEncryptedXml(wxMpService.getWxMpConfigStorage());
    }

    @Override
    public void mass() throws WxErrorException {

        //获取用户列表
        WxMpUserList wxUserList = wxMpService.getUserService().userList(null);

        for (String openid : wxUserList.getOpenids()) {
            WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
            massMessage.setMsgType(WxConsts.MassMsgType.TEXT);
            massMessage.setContent("消息内容");
            massMessage.getToUsers().add(openid);
            try {
                WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
                if (!StrUtil.equals("0", massResult.getErrorCode())) {
                    log.info("发送失败！openID为：{}", openid);
                    break;
                }
            } catch (WxErrorException e) {
                log.error("群发错误：{}", e.getMessage());
            }
        }
    }
}
